"use strict";
const path = require("path");
const UpdateRecord = require("./src/updateRecord/index");
// 版本自增
const getNextVersion = (version) => {
  let V4 = version.match(/\d+/g);
  let next = parseInt(V4.pop()) + 1;
  if (next === 100) {
    return [getNextVersion(V4.join(".")), 0].join(".");
  } else {
    V4.push(next);
    return V4.join(".");
  }
};
// 版本校验
const isValidVersion = (version) => {
  var reg = /^(\d+)\.(\d+)\.(\d+)$/;
  return reg.test(version);
};
// 版本升级
const updateVersion = (version, mode) => {
  if (!version) throw new Error("版本号格式错误：" + version);
  const vers = version.split(`-`);
  if (!isValidVersion(vers[0])) throw new Error("版本号格式错误：" + version);
  if (mode === "dev") {
    // return version;
    let v = vers[1] ? vers[1].split(".")[1] : "0";
    return `${vers[0]}-${mode}.${getNextVersion(v)}`;
  } else if (mode === "pro") {
    return getNextVersion(vers[0]);
  } else {
    let v = vers[1] ? vers[1].split(".")[1] : "0";
    return `${vers[0]}-${mode}.${getNextVersion(v)}`;
  }
};
// 版本更新
const handleVersion = (jsonFilePath, mode, field) => {
  const jsonContent = require(jsonFilePath);
  const originVersion = jsonContent ? jsonContent[field] : "";
  let newVersion = originVersion;
  return updateVersion(originVersion, mode);
};
class VersionsControl {
  constructor(options = {}) {
    this.config = options
  }
  apply(compiler) {
    // For webpack >= 4
    if (compiler.hooks) {
      if (this.config.mode === 'dev') {
        compiler.hooks.environment.tap("versionsControl", (state, callback) => {
          UpdateRecord.apply(this.config, callback);
        });
      } else {
        // 在编译器准备环境时调用，时机就在配置文件中初始化插件之后。
        compiler.hooks.beforeRun.tapAsync("versionsControl", (state, callback) => {
          UpdateRecord.apply(this.config, callback);
        });
      }
    }
    // For webpack < 4
    else {
      compiler.plugin("environment", (stats, callback) => {
        UpdateRecord.apply(this.config, callback);
      });
    }
  }
}

module.exports = VersionsControl;